<!-- Access Token Modal -->
<div class="modal fade" id="access_token_modal" tabindex="-1" aria-labelledby="access_token_modal_label" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="access_token_modal_label">Access Tokens</h1>
                <div style="float: right">
                    <i class="fi fi-br-expand px-3" id="expand-icon" style="cursor: pointer; float: left; opacity: 0.5"></i>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
            </div>
            <div class="modal-body">
                <div id="dTable" class="box-body table-responsive" style="padding:10px;">
                    <table id="access_token_modal_table" class="table" style="width:100%">
                        <thead>
                            <tr>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th>ID</th>
                                <th>Issued</th>
                                <th>Expires</th>
                                <th>User</th>
                                <th>Resource</th>
                                <th>Description</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" class="init">
    // Populate the access_token_modal_table table
    let accessTokenModalTable = new DataTable('#access_token_modal_table', {
        ajax: {
            url: '/api/list_access_tokens', dataSrc: ""
        },
        columns: [
            {
                className: 'dt-control',
                orderable: false,
                data: null,
                defaultContent: '',
                'width': '40px'
            },
            {
                className: 'active-control',
                orderable: false,
                data: null,
                defaultContent: '<i class="fi fi-br-check" style="cursor: pointer"></i>',
                'width': '40px'
            },
            {
                className: 'copy-control',
                orderable: false,
                data: null,
                defaultContent: '<i class="fi fi-rr-copy-alt" style="cursor: pointer"></i>',
                'width': '40px'
            },
            {
                className: 'delete-control',
                orderable: false,
                data: null,
                defaultContent: '<i class="fi fi-rr-trash" style="cursor: pointer"></i>',
                'width': '40px'
            },
            { data: 'id', 'width': '60px' },
            { data: 'issued_at', 'width': '170px' },
            { data: 'expires_at', 'width': '170px' },
            { data: 'user', 'width': '370px' },
            { data: 'resource', 'width': '370px' },
            { data: 'description' }
        ],
        order: [[4, 'desc']],
        autoWidth: false,
        createdRow: function (row, data, dataIndex) {
            if (new Date(data.expires_at) > new Date()) {
                $(row).children().addClass('bg-success-subtle').addClass('text-success-emphasis');
            } else {
                $(row).children().addClass('bg-danger-subtle').addClass('text-danger-emphasis');
            }
        }
    })

    accessTokenModalTable.on('click', 'td.dt-control', function (e) {
        let tr = e.target.closest('tr');
        let row = accessTokenModalTable.row(tr);

        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
        }
        else {
            // Open this row
            row.child(formatAccessToken(row.data())).show();
            Prism.highlightAll();
        }
    });

    accessTokenModalTable.on('click', 'td.active-control', function (e) {
        let tr = e.target.closest('tr');
        let row = accessTokenModalTable.row(tr);
        setActiveAccessToken(row.data().id);
        $('#access_token_modal').modal('hide');
    });

    accessTokenModalTable.on('click', 'td.copy-control', function (e) {
        let tr = e.target.closest('tr');
        let row = accessTokenModalTable.row(tr);
        copyToClipboard(row.data().accesstoken);
    });


    accessTokenModalTable.on('click', 'td.delete-control', function (e) {
        let tr = e.target.closest('tr');
        let row = accessTokenModalTable.row(tr);
        if (!confirm("Are you sure you want to delete access token with ID " + row.data().id + "?")) { return }
        deleteAccessToken(row.data().id);
        $('#access_token_modal_table').DataTable().ajax.reload(null, false);
    });

    function formatAccessToken(d) {
        // `d` is the original data object for the row
        let response = $.ajax({
            type: "GET",
            async: false,
            url: "/api/decode_token/" + d.id
        });
        var formatWrapper = $(
            '<dl style="word-wrap: break-word; word-break: break-all; max-width:100%">' +
            '<dt>Raw Token:</dt>' +
            '</dl>'
        );
        var formatCode = $('<code></code>').text(d.accesstoken);
        formatWrapper.append($('<dd></dd>').append(formatCode));
        formatWrapper.append($('<dt>Decoded Token:</dt>'));
        var formatPre = formatJsonCode(JSON.parse(response.responseText));
        formatWrapper.append($('<dd></dd>').append(formatPre));
        return formatWrapper;
    }

    $("#access_token_modal").on('click', 'i#expand-icon', function (e) {
        $("#access_token_modal .modal-dialog").toggleClass('modal-xl').toggleClass('modal-fullscreen')
        $("#access_token_modal i#expand-icon").toggleClass('fi-br-expand').toggleClass('fi-br-compress')
    })
</script>